$(function () {
    height()
    $(window).on("resize", function () {
        height()
    })
})
/**start与webview接口交互****************************************************************/
//注册回调函数，第一次连接时调用 初始化函数
connectWebViewJavascriptBridge(function (bridge) {
	bridge.init(function (message, responseCallback) {
		var responseData = '默认接收收到来自Java的数据，回传数据给你';
		responseCallback(responseData);
	});

	bridge.registerHandler("setImgPic", function (data, responseCallback) {
		var picList = eval('(' + data + ')');
		for (var i = 0; i < picList.length; i++) {
			var picPath = picList[i].picPath;
			var picHTML = '<div class="swiper-slide"><img class="uploadPicture" src="' + picPath + '"></div>';
			$(".addpic-div").prepend(picHTML);
		}
		//图片预览
		$('.uploadPicture').on("click", function () {
			var urlList = [];
			$(".uploadPicture").each(function (i) {
				var _url = $(this).attr("src");
				urlList.push(_url);
			})
			openPhotoSwipe(urlList);
		})
		var responseData = '指定接收收到来自Java的数据，回传数据给你';
		responseCallback(responseData);
	});
	
	bridge.registerHandler("setLoc", function (data, responseCallback) {
		var locObj = eval('(' + data + ')');
		createJQWithLocation(locObj.longitude, locObj.latitude);
		var responseData = '指定接收收到来自Java的数据，回传数据给你';
		responseCallback(responseData);
	});
	
	bridge.registerHandler("setScanCode", function (data, responseCallback) {
		alert(data);
		var dataObj = eval('(' + data + ')');
		var responseData = '指定接收收到来自Java的数据，回传数据给你';
		responseCallback(responseData);
	});
	KDDH.isHaveRegisterHandler=true;
})

//注册事件监听
function connectWebViewJavascriptBridge(callback) {
	if (window.WebViewJavascriptBridge) {
		callback(WebViewJavascriptBridge)
	} else {
		document.addEventListener(
			'WebViewJavascriptBridgeReady',
			function () {
				callback(WebViewJavascriptBridge)
			},
			false
		);
	}
}
//type="getPic"--获取图片
//type="getLoc"--获取坐标
function getInfoFromWebView(type, value) {
	//发送消息给java代码
	var data = { action: type, value: "" };
	if (value) {
		data = { action: type, value: JSON.stringify(value) }
	}
	if(type == "getOpenGaoDe"){
		data = { action: type, value: value }
	}
	data = JSON.stringify(data);
	if (window.WebViewJavascriptBridge != undefined) {
		//第一个参数要发送的数据 第二个参数js在被回调后具体执行方法，responseData为java层回传数据
		window.WebViewJavascriptBridge.send(data, function (responseData) {
			alert("回调成功" + type);
			alert('来自Java的回传数据： ' + responseData);
		});
	}
}

/**end  与webview接口交互****************************************************************/

//解析url传参
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return decodeURI(r[2]);
	return null;
}

// 设置高度
function height() {
//  var whdef = 100 / 1618; // 表示1920的设计图,使用100PX的默认值
//  var wH = window.innerHeight; // 当前窗口的高度
//  var wW = window.innerWidth; // 当前窗口的宽度
//  //设置最小宽度
//  if (wW < 1024) {
//      wW = 1024;
//  }
//  var rem = wW * whdef; // 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值
//  $('html').css('font-size', rem + "px");
    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    //设置最小宽度
    if (w < 300) {
        w = 300;
    }
    //index
//  $(".swiper-container .ulContent").css({
//      "height": (h - 60 - 45) + "px",
//      "width": (w - 30) + "px"
//  })
	$(".swiper-container .ulContent").css({
        "height": (h - 150) + "px",
    })
	$(".zs_layout .loadingMasker img").css({
        "margin-left": (w - 120)/2 + "px",
    })
}

function initBar(){
//	setNiceScroll(".tabcontainer .all .ulContent");
//	setNiceScroll(".tabcontainer .dcl .ulContent");
	setNiceScroll1(".tabcontainer .all .ulContent",".tabcontainer .all .ulContent ul");
	setNiceScroll1(".tabcontainer .dcl .ulContent",".tabcontainer .dcl .ulContent ul");
}


/**start将对象转换成字符串****************************************************************/
function json2str(it, prettyPrint) {
	return stringify(it, function (key, value) {
		if (value) {
			var tf = value.__json__ || value.json;
			if (typeof tf == "function") {
				return tf.call(value);
			}
		}
		return value;
	}, prettyPrint && this.toJsonIndentStr)
}

function stringify(value, replacer, spacer) {

	var undef;
	if (typeof replacer == "string") {
		spacer = replacer;
		replacer = null;
	}

	function stringify(it, indent, key) {
		if (replacer) {
			it = replacer(key, it);
		}
		var val, objtype = typeof it;
		if (objtype == "number") {
			return isFinite(it) ? it + "" : "null";
		}
		if (objtype == "boolean") {
			return it + "";
		}
		if (it === null) {
			return "null";
		}
		if (typeof it == "string") {
			return escapeString(it);
		}
		if (objtype == "function" || objtype == "undefined") {
			return undef;
		}

		if (typeof it.toJSON == "function") {
			return stringify(it.toJSON(key), indent, key);
		}
		if (it instanceof Date) {
			return '"{FullYear}-{Month+}-{Date}T{Hours}:{Minutes}:{Seconds}Z"'.replace(/\{(\w+)(\+)?\}/g, function (t, prop, plus) {
				var num = it["getUTC" + prop]() + (plus ? 1 : 0);
				return num < 10 ? "0" + num : num;
			});
		}
		if (it.valueOf() !== it) {

			return stringify(it.valueOf(), indent, key);
		}
		var nextIndent = spacer ? (indent + spacer) : "";

		var sep = spacer ? " " : "";
		var newLine = spacer ? "\n" : "";

		if (it instanceof Array) {
			var itl = it.length,
				res = [];
			for (key = 0; key < itl; key++) {
				var obj = it[key];
				val = stringify(obj, nextIndent, key);
				if (typeof val != "string") {
					val = "null";
				}
				res.push(newLine + nextIndent + val);
			}
			return "[" + res.join(",") + newLine + indent + "]";
		}

		var output = [];
		for (key in it) {
			var keyStr;
			if (typeof key == "number") {
				keyStr = '"' + key + '"';
			} else if (typeof key == "string") {
				keyStr = escapeString(key);
			} else {

				continue;
			}
			val = stringify(it[key], nextIndent, key);
			if (typeof val != "string") {

				continue;
			}

			output.push(newLine + nextIndent + keyStr + ":" + sep + val);
		}
		return "{" + output.join(",") + newLine + indent + "}";
	}
	return stringify(value, "", "");

};

function escapeString( /*String*/ str) {
	return ('"' + str.replace(/(["\\])/g, '\\$1') + '"').
		replace(/[\f]/g, "\\f").replace(/[\b]/g, "\\b").replace(/[\n]/g, "\\n").
		replace(/[\t]/g, "\\t").replace(/[\r]/g, "\\r");
}
/**end将对象转换成字符串****************************************************************/

//根据date日期对象，拼接出日期字符串
function getMyDateVal(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	var d = date.getDate();
	var h = date.getHours();
	var mi = date.getMinutes();
	var s = date.getSeconds();
	return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + (h < 10 ? '0' + h : h) + ':' + (mi < 10 ? '0' + mi : mi) + ':' + (s < 10 ? '0' + s : s);
}

//滚动条
function setNiceScroll(containerClass1) {
	$(containerClass1).niceScroll({
		cursorcolor: "#dfdfdf",
		autohidemode: false,
		// cursorborderradius: 4,
		background: '#f8f8f8',
		cursorminheight: 32,
		// disableoutline: true,
	}).show();
	$(containerClass1).niceScroll({
		cursorcolor: "#dfdfdf",
		autohidemode: false,
		// cursorborderradius: 4,
		background: '#f8f8f8',
		cursorminheight: 32,
		// disableoutline: true,
	}).resize();
}
//滚动条，优化滚动条位置不对问题
function setNiceScroll1(containerClass1, containerClass2) {
	$(containerClass1).niceScroll(containerClass2, {
		cursorcolor: "#dfdfdf",
		autohidemode: true,
		// cursorborderradius: 4,
		background: '#fff',
		cursorminheight: 32,
		disableoutline: true,
		cursorborder: "0px solid #fff",
		cursorwidth: "5px",
		nativeparentscrolling: true,
		preventmultitouchscrolling: true, // 防止多触点事件引发滚动
		disableoutline: true,
	}).show();
	$(containerClass1).niceScroll(containerClass2, {
		cursorcolor: "#dfdfdf",
		autohidemode: true,
		// cursorborderradius: 4,
		background: '#fff',
		cursorminheight: 32,
		disableoutline: true,
		cursorborder: "0px solid #fff",
		cursorwidth: "5px",
		nativeparentscrolling: true,
		preventmultitouchscrolling: true, // 防止多触点事件引发滚动
		disableoutline: true,
	}).resize();
}

//调用后台接口
function callAjax(_url, paramObj, callback) {
	$.ajax({
		type : "post",
		url : _url,
		data : paramObj,
		contentType : 'application/json',
		dataType : 'json',
		success : function(result) {
			if (callback) {
				callback(result);
			}
		}
	});
}

var taskObjList = [];
function getTask_LocalStorage(){
    var taskStr = localStorage.getItem('task');
//  var taskObjList = eval('(' + taskStr + ')');
    taskObjList = JSON.parse(taskStr);
    if(!taskObjList){
        taskObjList = [];
    }
    console.log(taskObjList);
}

function addNewTask_LocalStorage(dataObj,callBack){
    dataObj.status=0;
    dataObj.taskid=new Date().getTime();
    taskObjList.push(dataObj);
    localStorage.setItem('task',JSON.stringify(taskObjList));
    getTask_LocalStorage();
    callBack({
        msg:"success"
    });
}
//获取未完成任务列表
function getNoTaskList_LocalStorage(dataObj,callBack){
    var resultList=[];
    for(var i=0; i<taskObjList.length; i++){
        if(taskObjList[i].userid == dataObj.userid && taskObjList[i].status == 0){
            resultList.push(taskObjList[i]);
        }
    }
    callBack({
        data:resultList
    });
}
//获取已完成任务列表
function getYesTaskList_LocalStorage(dataObj,callBack){
    var resultList=[];
    for(var i=0; i<taskObjList.length; i++){
        if(taskObjList[i].userid == dataObj.userid && taskObjList[i].status == 1){
            resultList.push(taskObjList[i]);
        }
    }
    callBack({
        data:resultList
    });
}
//更新任务状态
function updateTaskStatus_LocalStorage(dataObj,callBack){
    var resultList=[];
    var updatetime = getMyDateVal(new Date());
    for(var i=0; i<taskObjList.length; i++){
        if(taskObjList[i].taskid == dataObj.taskid){
            taskObjList[i].status = dataObj.status;
            taskObjList[i].updatetime = updatetime;
        }
    }
    localStorage.setItem('task',JSON.stringify(taskObjList));
    getTask_LocalStorage();
    callBack({
        msg:"success"
    });
}

function deleteAllYesTask_LocalStorage(dataObj,callBack){
//  for(i=taskObjList.length-1; i>=0; i--){
//      if(taskObjList[i].userid == dataObj.userid && taskObjList[i].status == 1){
//          taskObjList.splice(i,1);
//      }
//  }
    var i = taskObjList.length;
    while(i--) {
        if(taskObjList[i].userid == dataObj.userid && taskObjList[i].status == 1){
            taskObjList.splice(i, 1);
        }
    }
    localStorage.setItem('task',JSON.stringify(taskObjList));
    getTask_LocalStorage();
    callBack({
        msg:"success"
    });
}
